/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   13-4-28 下午1:17 Created by dwzhang
 */
package com.jade.framework.startup.spring;

import java.net.URL;

import com.jade.framework.base.JadeSystem;
import com.jade.framework.startup.AbstractServerDeployer;
import com.jade.framework.startup.def.ServerDefinition;
import com.jade.framework.startup.def.SystemDefinition;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.support.FileSystemXmlApplicationContext;

/**
 * 使用Spring作为系统容器来启动。
 *
 * @author dwzhang
 * @version 1.0 13-4-28 下午1:17
 * @deprecated replaced by Server
 */
public class SpringServerDeployer extends AbstractServerDeployer
{
    private static SpringServerDeployer instance = new SpringServerDeployer();

    private SpringServerDeployer()
    {
    }

    public static SpringServerDeployer getInstance()
    {
        return instance;
    }

    public void deploy(String serverType)
    {
        JadeSystem.getLog().info("Start to deploy server " + serverType);
        ServerDefinition serverDefinition = SystemDefinition.getInstance().getServer(serverType);
        URL[] configList = serverDefinition.getConfigList();
        URL[] runList = serverDefinition.getRunList();
        String configFiles = StringUtils.join(toStringArray(configList, false), ',');
        String runFiles = StringUtils.join(toStringArray(runList, true), ',');
        JadeSystem.getLog().info("Property files:" + configFiles);
        JadeSystem.getLog().info("Context xml files:" + runFiles);
        JadeSystem.setProperty("jade.props", configFiles);
        FileSystemXmlApplicationContext applicationContext = new FileSystemXmlApplicationContext(
                toStringArray(runList, true));
        JadeSystem.getLog().info("Start application context...");
        applicationContext.start();
        JadeSystem.getLog().info("Start application context finished");
        applicationContext.registerShutdownHook();
    }

    public void deployWithConfig(String xmlConfig)
    {
        FileSystemXmlApplicationContext applicationContext = new FileSystemXmlApplicationContext(xmlConfig);
        applicationContext.start();
        applicationContext.registerShutdownHook();
    }

    protected String[] toStringArray(URL[] urls, boolean abs)
    {
        String[] array = new String[urls.length];
        for (int i = 0; i < array.length; i++) {
            if (abs) {
                array[i] = "file://" + urls[i].getPath();
                //array[i] = urls[i].getPath();
            }
            else {
                array[i] = urls[i].getPath();
            }
        }
        return array;
    }
}
